<template>
	<ge-page id="ge-page" >
		<van-search shape="round" @click="search" placeholder="搜索" :value="searchValue" />
		<van-tabs line-width="80rpx" @change="onTabsChange"  :active="dataType">
			<van-tab title="全部" name="all"></van-tab>
			<van-tab title="外卖单" name="waimai"></van-tab>
			<van-tab title="堂食单" name="tangshi"></van-tab>
			<!-- <van-tab title="待付款" name="pay"></van-tab> -->
			<!-- <van-tab title="待售后" name="after"></van-tab> -->
			<van-tab title="已完成" name="complete"></van-tab>
			
		</van-tabs>
		<view class="data-box">
			<scroll-view scroll-y="true" style="	height: calc(100vh - 400rpx);" @scrolltolower="onMore">
				<view class="cont-one" v-for="item in list" :key="item.order_id">
					<view class="order-num">
						<view class="">
							<span class="order-no">订单号：</span><span class="order-word">{{item.order_no}}</span>
						</view>
						<!-- <span class="order-status">{{payStatusEnum[item.pay_status]}}</span> -->
						<!-- <span class="order-status">{{item.pay_status}}</span> -->
						<span class="order-status">{{item.state_text}}</span>
						
					</view>
					<view class="product-info" v-for="goods in item.goods" :key="goods.order_goods_id" @click="handleTargetDetail(item.order_id)">
						<image class="product-img" :src="goods.goods_image" mode=""></image>
						<view class="info-right">
							<view class="info-name">{{goods.goods_name}}</view>
							<view class="price">
								{{goods.goods_props | goodsProps}}
							</view>
						</view>
						<view class="price-box">
							<view class="sum-price">
								￥{{goods.grade_goods_price}}
							</view>
							<view class="pro-num">
								×{{goods.total_num}}
							</view>
						</view> 
					</view>
					<view class="button-list">
						<!-- <view class="button-one remove-bg">
							{{orderStatus[item.order_status]}}
						</view> -->
						<block v-if="item.pay_status == 20 && item.delivery_type == 10 && item.delivery_status == 10  && item.receipt_status == 10 
						&& item.order_status != 20">
						  <view class="button-one active" @click="acceptOrder(item.order_id)">确认接单</view>
						</block>
						<block v-if="item.pay_status == 20 && item.delivery_type == 10 && item.delivery_status == 15  && item.receipt_status == 10">
						  <view class="button-one" style="background-color: crimson;" @click="deliveryBym(item.order_id)">确认配送</view>
						</block>
						<!-- <view class="button-one">
							确认收货
						</view>
						<view class="button-one remove-bg">
							订单备注
						</view>
						<view class="button-one remove-bg">
							修改金额
						</view> -->
					</view>
					<view class="remark">
						{{item.buyer_remark}}
					</view>
				</view>
			</scroll-view>

		</view>
	</ge-page>
</template>

<script>
	import { payStatusEnum,DeliveryStatusEnum, orderStatus } from '@/constant/constant';
	import {
		storageKey,
		appConfig
	} from '@/constant/config';
	const token = uni.getStorageSync(storageKey.token) || null;
	export default {
		data() {
			return {
				searchValue: '',
				query: {
					page: 1
				},
				list: [],
				dataType: 'all',
				payStatusEnum,
				isMore: false,
				orderStatus,
			}
		},
		onLoad(option) {
			if(this.list.length == 0){
			   this.fetchOrder();
			}
		},
		created() {
			const hrefUrl = location.href;
			
			function getUrlKey(name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(hrefUrl) || [,
					""
				])[1].replace(/\+/g, '%20')) || null;
			}
			const active = getUrlKey('active');
			if(active) this.dataType = active
		},
		filters: {
			goodsProps(goodsProps) {
				if(goodsProps){
					return goodsProps.map(d => d.value.name).join(' ')
				}
				 return ""
			}
		},
		methods: {
			search(e) {
				this.searchValue = e.detail;
				this.query = {
					searchValue: this.searchValue
				};
				this.list = [];
				if(this.list.length == 0){
					console.log(3)
				   this.fetchOrder();
				}
				
			},
			onTabsChange(e) {
        
				//if (this.dataType === e.detail.name) return
				// 初始化
				this.dataType = e.detail.name;
				this.searchValue = '';
				this.list = [];
				this.query = { page: 1 };
				this.fetchOrder();
			},
			onMore() {
				if (this.isMore) {
					const page = this.query.page || 1;
					this.query = {
						...this.query,
						page: page + 1
					}
					this.fetchOrder();
				}
			},
			/* acceptOrder(order_id){
				uni.api.acceptOrder({
					order_id: order_id
				}).then((res) => {
                     
					 if(res.err){
						 console.log(res.data)
					 uni.showToast({
					   title: '操作失败',
					   icon: 'error',
					   duration: 2000 // 提示框的显示时间，单位毫秒，默认1500
					 });
					 return
					 }

					  uni.showToast({
						title: '接单成功',
						icon: 'success',
						duration: 2000 // 提示框的显示时间，单位毫秒，默认1500
					  });
					  setTimeout(() => {
						 window.location.href = '/storeadmin';
					  }, 1000);
					})
			}, */
			acceptOrder(order_id) {  
				let app = this
			    uni.request({  
			        url: `${appConfig.host}/store/order.delivery/accept`,  
			        method: 'POST', // 根据你的API要求选择GET或POST  
					header: {
						'content-type': 'application/json;charset=utf-8',
						'Access-Token': token
					},
			        data: {  
			            order_id: order_id  
			        },  
			        success: (res) => {  
			            console.log(res.data); // 这里应该包含从后端返回的数据  
			            if (res.data.status !== 200) { 
							uni.showToast({
							  title: res.data.message,
							  icon: 'error',
							  duration: 2000 // 提示框的显示时间，单位毫秒，默认1500
							});
							return
			            } else{
							uni.showToast({
							  title: '接单成功',
							  icon: 'success',
							  duration: 2000 // 提示框的显示时间，单位毫秒，默认1500
							});
							
							setTimeout(() => {
							  this.list.forEach(obj => {
							    if (obj.order_id === order_id) {  
							      obj.delivery_status = 15;  
							    }  
							  }); 
							}, 1000);
							
						}
						 
			        },  
			        fail: (err) => {  
			            uni.showToast({
			              title: '请求失败:'+err,
			              icon: 'error',
			              duration: 2000 // 提示框的显示时间，单位毫秒，默认1500
			            });
			            return
			        }  
			    });  
			},
			deliveryBym(order_id){
				uni.api.deliveryBym({
					order_id: order_id
				}).then((res) => {
				  if(res.err){
					  console.log(JSON.stringify(res))
					uni.showToast({
					  title: '操作失败',
					  icon: 'error',
					  duration: 2000 // 提示框的显示时间，单位毫秒，默认1500
					});
					return
				   }

				  uni.showToast({
					title: '操作成功',
					icon: 'success',
					duration: 2000 // 提示框的显示时间，单位毫秒，默认1500
				  });
				  setTimeout(() => {
				    this.list.forEach(obj => {
				      if (obj.order_id === order_id) {  
				        obj.delivery_status = 20;  
				      }  
				    }); 
				  }, 1000);
			   })
			},
			fetchOrder() {
				const query = {
					...this.query,
					//searchType: -1, // 默认查询字段'订单号'
					page: this.query.page || 1,
					//orderSource: -1,
					//deliveryType: -1,
					//payMethod: null,
				}
				
				uni.api.getOrder({ dataType: this.dataType, ...query }).then(res => {
					if (res.list.current_page === res.list.last_page) {
						this.isMore = false;
					} else {
						this.isMore = true;
					}
					this.list = [...this.list, ...(res.list.data || [])];
				})
			},
			// 跳转到订单详情页
			handleTargetDetail(orderid) {
			  uni.navigateTo({
				  url: `/pages/order/detail/index?orderid=`+orderid
			  }) 
			},
		}
	}
</script>

<style scoped lang="scss">
	.data-box {

		.cont-one {
			margin: 20rpx auto 0;
			padding: 20rpx;
			box-sizing: border-box;
			background-color: #fff;
			border-radius: 20rpx;
			width: 700rpx;

			.order-num {
				font-size: 24rpx;
				display: flex;
				justify-content: space-between;
				margin-bottom: 10rpx;

				.order-status {
					color: orange;
					font-size: 28rpx;
				}
			}

			.product-info {
				display: flex;
				margin-top: 15rpx;

				.product-img {

					width: 120rpx;
					height: 120rpx;
					border-radius: 10rpx;
					margin-right: 20rpx;
				}

				.info-right {
					width: calc(100% - 300rpx);

					.info-name {
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 2;
						overflow: hidden;
						text-overflow: ellipsis;
					}



					.price {
						color: #999;
						font-size: 24rpx;
						margin-top: 5rpx;
					}
				}

				.price-box {
					width: 150rpx;
					text-align: right;
                    .sum-price{
						font-size: 34rpx;
					}
					.pro-num {
						color: #000;
						font-size: 34rpx;
						font-weight: bold;
					}
				}
			}

			.button-list {
				display: flex;
				justify-content: flex-end;

				.button-one {
					width: 120rpx;
					height: 50rpx;
					background-color: blue;
					color: #fff;
					font-size: 22rpx;
					border-radius: 25rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					margin-left: 20rpx;
				}

				.remove-bg {
					background-color: transparent;
					border: 1rpx solid #666;
					color: #000;
				}
			}
		}
	}
</style>